package com.ifnk.portaljava.dapWeb.socket;
/**
 * <p>Title: 发送数据到页面类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author WenSheng.Song.hlyt@gmail.com
 * @version 1.0
 */


import flex.messaging.MessageBroker;
import flex.messaging.messages.AcknowledgeMessage;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SendDataToFlex extends Thread {
	private Log loger = LogFactory.getLog(SendDataToFlex.class);
	private ClientProperty cp;
	private int count=0;
	//private int minSendFlag = 0;
//	private Long ppId;

	public SendDataToFlex(ClientProperty cp) {
		this.cp = cp;
//		this.ppId = id;
	}

	@Override
	public void run() {
		while (true) {
			if (cp.getData().isEmpty()) {
				count++;
				try {
					if (count > 8) {
						cp.sendThreads.remove(currentThread());
						break;
					} else {
						Thread.sleep(500);
						continue;
					}
				} catch (Exception ex) {
					Thread.currentThread().interrupt();
					loger.error("dapWeb  Exception " + ex.toString());
					cp.sendThreads.remove(currentThread());
					ex.printStackTrace();
					break;
				}
			} else {
				count = 0;
//				 loger.info("dapWeb Send CDR TO FLEX: "+"callTrace" + cp.getClientId() +" , cp.getData().size:"+ cp.getData().size());
//				Vector<Object> dataVt =  cp.getData();
				 int k =cp.getData().size();
				 if(k>500)k= 500;
				Object[] sendData =cp.getData().toArray(k);
				 loger.info(this.getId()+" dapWeb Send CDR TO FLEX: "+"callTrace" + cp.getClientId() +" ,sendData.length: "+ k);
				 sendPacketToFlex("callTrace" + cp.getClientId(), cp
						.getClientId(),sendData );
				 sendData = null;
//				 loger.info("dapWeb send cdr to flex success");
			}
		}
	}

	public void sendPacketToFlex(String subTopic, String clientId, Object obj) {
		// loger.info("sendPacketToFlex");
		MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
	
		AsyncMessage msg = new AsyncMessage();
		msg.setDestination("callTraceChannel");
		msg.setHeader("DSSubtopic", subTopic);
		msg.setClientId(clientId);
		msg.setMessageId(UUIDUtils.createUUID());
		msg.setTimestamp(System.currentTimeMillis());
		msg.setBody(obj);
		@SuppressWarnings("unused")
		AcknowledgeMessage Ack = messageBroker.routeMessageToService(msg, null);
		
	}
}
